// content.js - 内容脚本，在网页中运行

// 获取浏览器扩展API（支持Chrome和Edge）
function getExtensionAPI() {
    // 优先使用browser API（Edge）
    if (typeof browser !== 'undefined' && browser.runtime) {
        return browser;
    }
    // 回退到chrome API（Chrome）
    if (typeof chrome !== 'undefined' && chrome.runtime) {
        return chrome;
    }
    return null;
}

const extensionAPI = getExtensionAPI();

// 监听DOM检测元素 (保持原有功能)
const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
        if (mutation.type === 'childList') {
            mutation.addedNodes.forEach((node) => {
                if (node.nodeType === Node.ELEMENT_NODE) {
                    const element = node;
                    if (element.id === 'yunlianfangzhou-detection' && 
                        element.getAttribute('data-plugin-name') === '闪零授权插件') {
                        
                        if (element.getAttribute('data-detected') !== 'true') {
                            element.setAttribute('data-detected', 'true');
                            element.setAttribute('data-version', '1.0.0');
                            element.setAttribute('data-response-time', Date.now());
                            
                            // 新增：提供扩展ID
                            if (element.getAttribute('data-request-extension-id') === 'true') {
                                element.setAttribute('data-extension-id', extensionAPI.runtime.id);
                            }
                        }
                    }
                }
            });
        }
    });
});

// 开始观察DOM变化
observer.observe(document.body, {
    childList: true,
    subtree: true
});

// 主动检查是否已有检测元素
function checkExistingDetectionElements() {
    const existingElement = document.getElementById('yunlianfangzhou-detection');
    if (existingElement && existingElement.getAttribute('data-plugin-name') === '闪零授权插件') {
        if (existingElement.getAttribute('data-detected') !== 'true') {
            existingElement.setAttribute('data-detected', 'true');
            existingElement.setAttribute('data-version', '1.0.0');
            existingElement.setAttribute('data-response-time', Date.now());
            
            // 新增：提供扩展ID
            if (existingElement.getAttribute('data-request-extension-id') === 'true') {
                existingElement.setAttribute('data-extension-id', extensionAPI.runtime.id);
            }
        }
    }
}

// 页面加载完成后立即检查
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', checkExistingDetectionElements);
} else {
    checkExistingDetectionElements();
}

// 定期检查检测元素（每500ms检查一次，持续5秒）
let checkCount = 0;
const maxChecks = 10;
const checkInterval = setInterval(() => {
    checkExistingDetectionElements();
    checkCount++;
    if (checkCount >= maxChecks) {
        clearInterval(checkInterval);
    }
}, 500);

// 监听来自Web页面的消息 (window.postMessage)
window.addEventListener('message', (event) => {
    // 安全检查
    if (event.source !== window) return;
    
    // 只处理我们自己的消息类型，避免处理其他脚本的消息
    if (event.data && typeof event.data === 'object' && event.data.type === 'FROM_PAGE') {
        
        switch (event.data.action) {
            case 'ping':
                // 发送响应回Web页面
                window.postMessage({
                    type: 'FROM_EXTENSION',
                    messageId: event.data.messageId,
                    response: {
                        success: true,
                        version: '1.0.0',
                        pluginName: '闪零授权插件',
                        message: 'Content script响应正常 (window.postMessage)'
                    }
                }, '*');
                break;
                
            case 'clearAndWaitForCookies':
                // 转发到background script
                extensionAPI.runtime.sendMessage({
                    action: 'clearAndWaitForCookies',
                    loginUrl: event.data.loginUrl,
                    cookieDomain: event.data.cookieDomain,
                    loginKeyword: event.data.loginKeyword
                }, (response) => {
                    if (extensionAPI.runtime.lastError) {
                        window.postMessage({
                            type: 'FROM_EXTENSION',
                            messageId: event.data.messageId,
                            response: { 
                                success: false, 
                                error: 'Content script转发消息失败: ' + extensionAPI.runtime.lastError.message 
                            }
                        }, '*');
                    } else {
                        window.postMessage({
                            type: 'FROM_EXTENSION',
                            messageId: event.data.messageId,
                            response: response
                        }, '*');
                    }
                });
                break;
                
            case 'getStoredCookies':
                // 转发到background script
                extensionAPI.runtime.sendMessage({
                    action: 'getStoredCookies'
                }, (response) => {
                    if (extensionAPI.runtime.lastError) {
                        window.postMessage({
                            type: 'FROM_EXTENSION',
                            messageId: event.data.messageId,
                            response: { 
                                success: false, 
                                error: 'Content script转发getStoredCookies消息失败: ' + extensionAPI.runtime.lastError.message 
                            }
                        }, '*');
                    } else {
                        window.postMessage({
                            type: 'FROM_EXTENSION',
                            messageId: event.data.messageId,
                            response: response
                        }, '*');
                    }
                });
                break;
                
            case 'setCookiesAndOpenUrl':
                // 转发到background script
                extensionAPI.runtime.sendMessage({
                    action: 'setCookiesAndOpenUrl',
                    cookies: event.data.cookies,
                    targetUrl: event.data.targetUrl
                }, (response) => {
                    if (extensionAPI.runtime.lastError) {
                        window.postMessage({
                            type: 'FROM_EXTENSION',
                            messageId: event.data.messageId,
                            response: { 
                                success: false, 
                                error: 'Content script转发setCookiesAndOpenUrl消息失败: ' + extensionAPI.runtime.lastError.message 
                            }
                        }, '*');
                    } else {
                        window.postMessage({
                            type: 'FROM_EXTENSION',
                            messageId: event.data.messageId,
                            response: response
                        }, '*');
                    }
                });
                break;
                
            default:
                window.postMessage({
                    type: 'FROM_EXTENSION',
                    messageId: event.data.messageId,
                    response: { success: false, error: '未知操作' }
                }, '*');
        }
    }
    // 忽略其他类型的消息，避免干扰页面其他脚本
});

// 监听来自Background的消息
extensionAPI.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.type === 'AUTH_SUCCESS') {
        // 转发授权成功消息到Web页面
        window.postMessage({
            type: 'FROM_EXTENSION',
            action: 'authSuccess',
            message: request.message
        }, '*');
    } else if (request.type === 'AUTH_CANCELLED') {
        // 转发登录取消/标签页关闭消息到Web页面
        window.postMessage({
            type: 'FROM_EXTENSION',
            action: 'authCancelled',
            message: request.message
        }, '*');
    }
});
